#-*-coding:utf-8-*-
import os
import sys
import time
import shutil
from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *

class InfoTextWidget(QWidget):
    def __init__(self,current_opition_path,index):
        super(InfoTextWidget,self).__init__()
        #全局变量
        self.username='' #当前用户名
        self.text=''     #当前文本内容
        self.date=''     #当前日期
        self.current_opition_path=current_opition_path #当前意见真实路径
        self.index=index #当前item索引
        self.info_save_path = ''#当前保存绝对路径地址
        self.img_path = ''  # 当前图像路径,虽然没有，防止双击报错

        self.mainLayout=QVBoxLayout()


        self.user_label=QLabel('Master')
        self.user_label.setFont(QFont('',12,75))
        self.user_label.setAlignment(Qt.AlignLeft)
        self.opinion_text_plain=QTextEdit()
        # self.opinion_text_plain.setFocusPolicy(Qt.NoFocus)
        self.opinion_text_plain.setReadOnly(True)
        self.time_label=QLabel('2019-07-07')
        self.time_label.setAlignment(Qt.AlignRight)
        self.mainLayout.addWidget(self.user_label)
        self.mainLayout.addWidget(self.opinion_text_plain)
        self.mainLayout.addWidget(self.time_label)

        self.setLayout(self.mainLayout)

    def initData(self,tupleInfo):
        '''
        创建该组件后设置里面内容
        :param tupleInfo: eg:(username,text,date) 分别是(用户名,文本内容,日期)
        :return:
        '''
        self.username=tupleInfo[0]
        self.text=tupleInfo[1]
        self.date=tupleInfo[2]
        self.__setText(self.username,self.text,self.date)
        # index_dir=os.path.join(self.current_opition_path,str(tupleInfo[3]))
        # self.info_save_path =os.path.join(index_dir,'info')#文本最终路径
    def __setText(self,username,text,date):
        '''
        初始化时，生成对应内容
        :param username:
        :param text:
        :param date:
        :return:
        '''
        self.user_label.setText(username+':')
        self.opinion_text_plain.setText(text)
        self.time_label.setText(date)

    def __save(self,path,username,text,date):
        '''
        保存本地
        :param path:
        :param username:
        :param text:
        :param date:
        :param index:不用了
        :return:
        '''
        tuple_temp=(username,text,date)
        # if not os.path.exists(path):
        #     os.makedirs(path)
        with open(path,'w',encoding='utf=8') as w:
            w.write(str(tuple_temp))

    def setText(self,username,text):
        '''
        设置文本内容
        :param username:当前用户
        :param text:
        :return:
        '''
        self.user_label.setText(username+':')
        self.opinion_text_plain.setText(text)
        date=time.strftime("%Y-%m-%d %H:%M:%S")
        self.time_label.setText(date)

        index_dir=os.path.join(self.current_opition_path,str(self.index))
        if not os.path.exists(index_dir):
            os.makedirs(index_dir)
        self.info_save_path =os.path.join(index_dir,'info')#文本最终路径

        self.__save(self.info_save_path,username,text,date)


class InfoImgWidget(QWidget):
    '''
    存图片，但是也会有info文件， 用来记录时间、用户等信息
    规则，因为一个文件夹存一个，本地的图片名称都叫img.png
    '''
    def __init__(self,current_opition_path,index):
        super(InfoImgWidget,self).__init__()

        self.mainLayout=QVBoxLayout()
        #全局变量
        self.username='' #当前用户名
        self.text=''     #当前文本内容
        self.date=''     #当前日期
        self.index=index #当前item索引
        self.current_real_shot_path=''
        self.current_opinion_path=current_opition_path#当前意见信息存储地址固定的在shot/opinion/opinion文件当中
        self.info_save_path = ''#当前保存绝对路径地址
        self.img_path = ''  # 当前图像路径

        self.user_label=QLabel('Master')
        self.user_label.setFont(QFont('',12,75))
        self.user_label.setAlignment(Qt.AlignLeft)
        self.opinion_img=QLabel()


        self.time_label=QLabel('2019-07-07')
        self.time_label.setAlignment(Qt.AlignRight)
        self.mainLayout.addWidget(self.user_label)
        self.mainLayout.addWidget(self.opinion_img)
        self.mainLayout.addWidget(self.time_label)

        self.setLayout(self.mainLayout)

        # self.cp=QApplication.clipboard()
        # self.opinion_img.setPixmap(self.cp.pixmap())

    def initData(self,tupleInfo,index):
        '''
        读取本地信息初始化效果
        :param tupleInfo: eg (username,text,date) 分别是(用户名,文本内容,日期),text=''
        :param index: 索引
        :return:
        '''
        self.username=tupleInfo[0]

        self.date=tupleInfo[2]
        index_path=os.path.join(self.current_opinion_path,str(index))
        self.img_path=os.path.join(index_path,'img.png')

        pix=QPixmap(self.img_path)
        self.__setImg(self.username,self.date,pix)


    def setImg(self,username,img):
        '''
        设置文本内容
        :param username:当前用户
        :param img: pixmap类型
        :return:
        '''
        self.user_label.setText(username+':')
        self.opinion_img.setPixmap(img)
        date=time.strftime("%Y-%m-%d %H:%M:%S")
        self.time_label.setText(date)

        index_dir=os.path.join(self.current_opinion_path,str(self.index))
        if not os.path.exists(index_dir):
            os.makedirs(index_dir)
        self.info_save_path =os.path.join(index_dir,'info')#文本最终路径
        img_save_path=os.path.join(index_dir,'img.png')#图片保存路径
        self.img_path=img_save_path
        self.__save( self.info_save_path,img_save_path,username,'',img,date)

    def __setImg(self,username,date,pix):
        '''
        初始化时，生成对应内容
        :param username:
        :param pix:
        :param date:
        :return:
        '''
        self.user_label.setText(username+':')
        self.opinion_img.setPixmap(pix)
        self.time_label.setText(date)




    def __test(self,username,img):
        '''
        设置文本内容
        :param username:当前用户
        :param text:
        :return:
        '''
        self.user_label.setText(username+':')
        self.opinion_img.setPixmap(img)
        date=time.strftime("%Y-%m-%d %H:%M:%S")
        self.time_label.setText(date)

    def __save(self,info_path,img_path,username,text,pix,date):
        '''
        保存本地
        :param path:
        :param username:
        :param text:
        :param date:
        :param pix:
        :return:
        '''
        tuple_temp=(username,text,date)
        with open(info_path,'w',encoding='utf=8') as w:
            w.write(str(tuple_temp))

        pix.save(img_path)



class Opinion(QWidget):
    '''
    还是以一个组件一个文件夹的形式来存储，这样就可以直接读取不分图片或文本
    '''
    def __init__(self,username):
        super(Opinion,self).__init__()

        self.mainLayout=QVBoxLayout()
        #全局变量

        self.main_list = []  # 将所有信息添加到这里
        self.username=username
        self.current_real_shot_path=''#当前镜头名称
        self.current_opinion_path=''#当前意见路径

        self.opinion_list=QListWidget()
        self.input_layout=QHBoxLayout()
        self.input_edit=QTextEdit()
        self.input_edit.setMaximumHeight(80)
        # self.img_label=QLabel('')
        self.btn=QPushButton('确定')
        self.btn.clicked.connect(self.__textBtn)
        self.btn.setMinimumSize(50,80)
        self.input_layout.addWidget(self.input_edit)

        # self.input_layout.addWidget(self.img_label)
        self.input_layout.addWidget(self.btn)
        self.mainLayout.addWidget(self.opinion_list)
        self.mainLayout.addLayout(self.input_layout)
        self.setLayout(self.mainLayout)

        # opinion_list添加右击菜单
        self.opinion_list.setContextMenuPolicy(Qt.CustomContextMenu)
        self.opinion_list.customContextMenuRequested.connect(self.__rightMenu)

        #opinion_list添加双击
        self.opinion_list.doubleClicked.connect(self.__showImg)
        #获取剪切板
        self.clipboard=QApplication.clipboard()


    def setCurrentOpinionPath(self, current_shot_path):
        '''
        从主窗口传来的当前真实镜头路径
        :param current_shot_path:
        :return:
        '''
        self.current_real_shot_path = current_shot_path
        if current_shot_path != '':
            self.current_opinion_path = os.path.join(self.current_real_shot_path, 'opinion')

    def showList(self):
        '''
        点击镜头后刷新当前返修列表，因为只实例化一个窗口，所以要清除掉当前的所有item
        关键是读取info里存的信息.当info是纯文本时，就读取文本内容，当是图片信息时就读取图片，因为一开始分的清，
        所以该索引目录下如果有2个文件，那么就是存图片文件
        :return:
        '''
        self.opinion_list.clear()
        index_info_list=os.listdir(self.current_opinion_path)#当前opinion总目录下所有已存意见目录
        if index_info_list !=[]:
            for i in index_info_list:
                index_info_path=os.path.join(self.current_opinion_path,i)#每个索引文件目录，
                info_path = os.path.join(index_info_path, 'info')
                count=len(os.listdir(index_info_path))
                if count<2:#只存在文本
                    temp_tuple=()
                    with open(info_path,'r',encoding='utf-8') as r:
                        temp_tuple=eval(r.read())
                    self.__initText(temp_tuple,int(i))

                else:#是图片
                    # img_path = os.path.join(self.current_opinion_path, 'img.png')
                    temp_tuple=()
                    with open(info_path,'r',encoding='utf-8') as r:
                        temp_tuple=eval(r.read())
                    self.__initImg(temp_tuple,int(i))

    def __rightMenu(self):
        self.menu = QMenu()

        self.copyImgAction = QAction(u'粘贴图片', self)
        self.copyImgAction.triggered.connect(self.__copyImgBtn)
        self.menu.addAction(self.copyImgAction)


        self.deleteAction = QAction(u'删除', self)
        self.deleteAction.triggered.connect(self.__deleteBtn)
        self.menu.addAction(self.deleteAction)

        self.menu.exec_(QCursor.pos())




    def __initText(self,tuple_info,index):
        '''
        初始化本地文本信息
        :param tuple: eg:(username,text,date)
        :param index: 索引
        :return:
        '''
        # username=tuple_info[0]
        # text=tuple_info[1]
        # date=tuple_info[2]
        item = QListWidgetItem()
        item.setSizeHint(QSize(200, 150))
        new_info = InfoTextWidget(self.current_opinion_path, index)
        new_info.initData(tuple_info)
        self.opinion_list.addItem(item)
        self.opinion_list.setItemWidget(item, new_info)

    def __initImg(self,tuple_info,index):
        '''
        初始化图片
        :param tuple_info:
        :param index:
        :return:
        '''
        item = QListWidgetItem()
        item.setSizeHint(QSize(200, 150))
        new_info = InfoImgWidget(self.current_opinion_path, index)
        new_info.initData(tuple_info,index)
        self.opinion_list.addItem(item)
        self.opinion_list.setItemWidget(item, new_info)




    def __showImg(self):
        currentItem=self.opinion_list.currentItem()
        widget=self.opinion_list.itemWidget(currentItem)
        img_path=widget.img_path
        print(img_path)
        if img_path !='':
            os.startfile(img_path)

    def __textBtn(self):
        text=self.input_edit.toPlainText()
        if text:
            print(text)
            index=self.opinion_list.count()
            new_info=InfoTextWidget(self.current_opinion_path,index)
            new_info.setText(self.username,text)

            item=QListWidgetItem()
            item.setSizeHint(QSize(200, 150))
            self.opinion_list.addItem(item)
            self.opinion_list.setItemWidget(item,new_info)

            self.main_list.append(new_info)
            self.input_edit.setText('')



    def __copyImgBtn(self):
        mimeData=self.clipboard.mimeData()
        if mimeData.hasImage():
            count=self.opinion_list.count()
            new_img=InfoImgWidget(self.current_opinion_path,count)
            new_img.setImg(self.username,self.clipboard.pixmap())
            item=QListWidgetItem()
            item.setSizeHint(QSize(200, 150))
            self.opinion_list.addItem(item)
            self.opinion_list.setItemWidget(item,new_img)

            self.main_list.append(new_img)



    def __deleteBtn(self):
        row=self.opinion_list.currentIndex().row()
        # print(row)
        self.opinion_list.takeItem(row)
        index_path=os.path.join(self.current_opinion_path,str(row))
        try:
            shutil.rmtree(index_path)
        except:
            QMessageBox.information(self,'提示','当前目录下有文件正在使用')


if __name__ == '__main__':
    app=QApplication(sys.argv)
    # o=Opinion()
    # o.show()
    info_path=r'F:\PycharmOut\BrickMover\Sample\Projects\X战警\包装\04\a1\opinion'
    info=InfoTextWidget(info_path,0)
    info.setText('老张','哈哈哈')

    # info=InfoImgWidget()
    info.show()

    sys.exit(app.exec_())
